﻿using DongFangGuoKai.WMS.ApiService;
using DongFangGuoKai.WMS.IApiService;
using DongFangGuoKai.WMSPlatform.Core;
using DongFangGuoKai.WMSPlatform.Domain.Model;
using DongFangGuoKai.WMSPlatform.Domain.Models;
using DongFangGuoKai.WMSPlatform.Domain.QueceModels;

namespace DongFangGuoKai.WMSPlatform.WebApi.BackgroundTakss
{
    public class CallNumberBackgroundService : BackgroundService
    {

        BackManagerOptions options = new BackManagerOptions();
        public CallNumberBackgroundService(Action<BackManagerOptions> options, IServiceProvider serviceProvider)
        {
            options.Invoke(this.options);
            ServiceProvider = serviceProvider;
        }

        public IServiceProvider ServiceProvider { get; }
        public ILogger<CallNumberBackgroundService> Logger { get; set; }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            // 延迟启动
            await Task.Delay(options.CheckTime, stoppingToken);

            Logger = ServiceProvider.GetRequiredService<ILogger<CallNumberBackgroundService>>();
            //判断如果令牌是否取消
            while (!stoppingToken.IsCancellationRequested)
            {
                var _repoQueceRecard = ServiceProvider.GetRequiredService<SimpleRepositroy<t_QueceRecard>>();

                //可执行叫号队列
                var waitDisPlayQueceRecards = await _repoQueceRecard.GetListAsync(t => t.Status == 1);
                if (waitDisPlayQueceRecards?.Count > 0)
                {
                    var queceApiService = ServiceProvider.GetRequiredService<QueceSystemService>();
                    var limsApiService = ServiceProvider.GetRequiredService<ILIMSService>();
                    foreach (t_QueceRecard waitQueceItem in waitDisPlayQueceRecards)
                    {

                        try
                        {
                            string windowCode = waitQueceItem.CounterNo;
                            string billNo = waitQueceItem.BillNO;
                            bool result = false;

                            //是否缴费
                            var limsResult = limsApiService.QueryTrustInfo(billNo);
                            if (!(limsResult.success && limsResult.data.isPay == 1 || limsResult.data.isGuarantee == 1))
                            {
                                waitQueceItem.Msg = "未缴费！";
                                _repoQueceRecard.Update(waitQueceItem);

                                continue;
                            }

                            //找窗口号_已排队未下出库单
                            if (string.IsNullOrEmpty(windowCode))
                            {
                                //出库单  
                                var context = ServiceProvider.GetRequiredService<WMSPlatformContext>();
                                var shippingOrderDetail = context.TShippingOrderDetails.FirstOrDefault(t => t.OrderSn == waitQueceItem.BillNO);
                                if (shippingOrderDetail != null)
                                {
                                    //出库单详情
                                    var shippingLockCell = context.TShippingLockCells.FirstOrDefault(t => t.OrderId == shippingOrderDetail.Id);
                                    windowCode = shippingLockCell.WindowCode;
                                    waitQueceItem.CounterNo = windowCode;
                                    result = true;
                                }
                                else
                                {
                                    waitQueceItem.Msg = "未找到出库窗口号！";
                                    _repoQueceRecard.Update(waitQueceItem);
                                
                                    continue;
                                }


                            }

                            string interfaceName = "insertqueue";//调用方法名
                            string number = waitQueceItem.Number == null ? "" : waitQueceItem.Number;  //排队号
                            string typeId = "1";  //业务类型取样
                            QueceResultRespone? res;

                            //显示
                            AddQueceModel displayModel = new AddQueceModel()
                            {
                                bookid = billNo,
                                counterno = windowCode,
                                number = number,
                                serialid = typeId,
                                status = "0",
                                interfacename = interfaceName
                            };
                            res = queceApiService.AddQuece(displayModel);
                            waitQueceItem.DisPlayDate = DateTime.Now;
                            waitQueceItem.DisplayStatus = res.succ == "0" ? true : false;
                            waitQueceItem.Msg = "显示失败：" + res.msg;
                            if (res.succ == "1")
                            {
                                waitQueceItem.Status = 3;
                                _repoQueceRecard.Update(waitQueceItem);
                                Logger.LogError($"委托单号：{waitQueceItem.BillNO}，调用叫号机Api执行失败：{res.msg}");
                                continue;

                            }

                            //呼叫
                            AddQueceModel callmodel = new AddQueceModel()
                            {
                                bookid = billNo,
                                counterno = windowCode,
                                number = number,
                                serialid = typeId,
                                status = "1",
                                interfacename = interfaceName
                            };
                            res = queceApiService.AddQuece(callmodel);
                            waitQueceItem.CallDate = DateTime.Now;
                            waitQueceItem.CallStatus = res.succ == "0" ? true : false;
                            waitQueceItem.Msg = "叫号失败：" + res.msg;

                            if (res.succ == "1")
                            {
                                waitQueceItem.Status = 3;
                                _repoQueceRecard.Update(waitQueceItem);
                                Logger.LogError($"委托单号：{waitQueceItem.BillNO}，调用叫号机Api执行失败：{res.msg}");
                                continue;

                            }
                            waitQueceItem.Status = 2;
                            waitQueceItem.Msg = null;
                            _repoQueceRecard.Update(waitQueceItem);
                           
                        }
                        catch (Exception ex)
                        {
                            waitQueceItem.Status = 3;
                            waitQueceItem.Msg = ex.Message;
                            _repoQueceRecard.Update(waitQueceItem);
                            Logger.LogError(ex.Message);

                        }


                    }
                }


                await Task.Delay(options.CheckTime, stoppingToken);
            }
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine($"{options.Name}由于进程退出，正在执行清理工作");

            return base.StopAsync(cancellationToken);
        }


    }
}
